package com.fw.system.web.service.impl;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fw.common.AliComm;
import com.fw.constant.Constant;
import com.fw.enums.LogsModelEnum;
import com.fw.enums.LogsTypeEnum;
import com.fw.exception.BaseException;
import com.fw.system.web.dao.FwShangjiaDealMapper;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.form.ShopIngShangJiaForm;
import com.fw.system.web.model.vo.ShangjiaDealVo;
import com.fw.system.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 商甲交易,买卖表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-06-08
 */
@Service
public class FwShangjiaDealServiceImpl extends ServiceImpl<FwShangjiaDealMapper, FwShangjiaDeal> implements IFwShangjiaDealService {


    @Autowired
    private IFwLockStorageService lockStorageService;
    @Autowired
    private FwShangjiaDealMapper shangjiaDealMapper;
    @Autowired
    private IFwShangjiaService shangjiaService;
    @Autowired
    private IFwRuleDatasService ruleDatasService;
    @Autowired
    private IFwMoneysService moneysService;
    @Autowired
    private IFwLogsService logsService;
    @Autowired
    private IFwUserService userService;
    @Autowired
    private AliComm aliComm;

    public List<ShangjiaDealVo> findDealList(String type) {
        return shangjiaDealMapper.findDealList(type);
    }

    /**
     * 购买商甲
     *
     * @param shopIngShangJiaForm
     */
    public void ShopIngShangJia(ShopIngShangJiaForm shopIngShangJiaForm) {

        //验证购买的数量和卖出的数量
        //查询用户购买商甲的记录数据
        FwShangjiaDeal dealServiceOne = shangjiaDealMapper.selectOne(Wrappers.<FwShangjiaDeal>lambdaQuery().eq(FwShangjiaDeal::getId, shopIngShangJiaForm.getId()));
        if (dealServiceOne.getCount().compareTo(shopIngShangJiaForm.getCount()) < 0) {
            return;
        }
        //获取用户信息
        FwUser user = userService.selectFwUserById(shopIngShangJiaForm.getUserId());

        //获取消费总额
        BigDecimal multiply = shopIngShangJiaForm.getMoney()/*.multiply(shopIngShangJiaForm.getCount())*/;
        //新增买入方支付宝消费收支日志
        logsService.saveLogs(shopIngShangJiaForm.getUserId(), shopIngShangJiaForm.getUserId(), LogsTypeEnum.MONEY_CONSUMPTION.getTypeName(), LogsModelEnum.ALI_PAY.getModelName(), "买入" + shopIngShangJiaForm.getCount() + "商甲", multiply.toString());

        //给买方发放商甲
        FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, shopIngShangJiaForm.getUserId()));
        BigDecimal shangJia = moneys.getShangJia();

        //获取购买商甲数量
        BigDecimal count = shopIngShangJiaForm.getCount();
        BigDecimal add = shangJia.add(count);
        moneys.setShangJia(add);
        moneysService.updateById(moneys);

        //新增买入方商甲收支日志
        logsService.saveLogs(shopIngShangJiaForm.getUserId(), shopIngShangJiaForm.getUserId(), LogsTypeEnum.MONEY_BUY.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "买入" + shopIngShangJiaForm.getCount() + "商甲", multiply.toString());
        //调用锁仓方法
        moneysService.extracted(user.getId(),moneys);


        //修改该条数据的数量
        BigDecimal oneCount = dealServiceOne.getCount();
        BigDecimal subtract = oneCount.subtract(shopIngShangJiaForm.getCount());
        dealServiceOne.setCount(subtract);//设置交易后的该条商甲数据的数量
        dealServiceOne.setUpdateBy(user.getUserName());//设置买入人
        dealServiceOne.setUpdateTime(LocalDateTime.now());//设置卖出时间
        if (subtract.compareTo(new BigDecimal("0")) <= 0) {
            //如果此数据的商甲数量已售完,将该数据状态改为已售出
            dealServiceOne.setType(Constant.ShopIngShangJiaType.IS_TYPE_SUCCESS);
        }
        dealServiceOne.setIsLock(0);
        shangjiaDealMapper.updateById(dealServiceOne);
        //新增卖出方商甲收支日志
        logsService.saveLogs(dealServiceOne.getUserId(), dealServiceOne.getUserId(), LogsTypeEnum.MONEY_SELL.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "卖出" + shopIngShangJiaForm.getCount() + "商甲", multiply.toString());
        //新增卖出方支付宝收支日志
        logsService.saveLogs(dealServiceOne.getUserId(), dealServiceOne.getUserId(), LogsTypeEnum.MONEY_INCOME.getTypeName(), LogsModelEnum.ALI_PAY.getModelName(), "卖出" + shopIngShangJiaForm.getCount() + "商甲", multiply.toString());


    }

    /**
     * 卖出商甲
     *
     * @param shopIngShangJiaForm
     */
    public void shopPay(ShopIngShangJiaForm shopIngShangJiaForm) {
        //获取卖出人信息
        FwShangjiaDeal deal = shangjiaDealMapper.selectOne(Wrappers.<FwShangjiaDeal>lambdaQuery().eq(FwShangjiaDeal::getId, shopIngShangJiaForm.getId()));
        String userId = deal.getUserId();
        FwUser fwUser = userService.selectFwUserById(userId);
        //扣除手续费
        FwRuleDatas ruleDatas = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.BECOME_PAY_MONEY_ID));
        //获取手续费比例
        BigDecimal ruleCount = ruleDatas.getRuleCount();
        BigDecimal multiply = ruleCount.multiply(new BigDecimal("0.01"));
        //获取金额
        BigDecimal money = shopIngShangJiaForm.getMoney();
        //获取手续费
        BigDecimal decimal = money.multiply(multiply);
        //金额减去手续费,拿到实际发放金额
        BigDecimal subtract = money.subtract(decimal);

        try {   //卖出人支付宝绑定手机号,金额
            aliComm.aliTransfer(fwUser.getAliPhone(), new BigDecimal(String.format("%.2f", subtract)),fwUser.getAliUserName());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

    }

    /**
     * 分红  todo 此工具方法可做定时任务,指定多久调用一次,或是做成后台接口,由甲方手动点击操作
     */
    public synchronized void bonus() {
        //验证本月是否已经分红
        List<FwLogs> fwLogsList = logsService.list(Wrappers.<FwLogs>lambdaQuery().eq(FwLogs::getBuiId, "1").eq(FwLogs::getIsType,LogsTypeEnum.SYS_BONUS.getTypeName()).eq(FwLogs::getModelName,LogsModelEnum.SYS_BONUS.getModelName()).eq(FwLogs::getCreateBy, "1")
                .last("AND DATE_FORMAT( create_time, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' ) "));
        if (fwLogsList.isEmpty()) {
            //获取用户锁仓数据最近一个月的不参与
            List<FwLockStorage> storages = lockStorageService.listStorages();
            //获取分红比例
            FwRuleDatas datas = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.BONUS));
            BigDecimal ruleCount = datas.getRuleCount();
            if (storages.size() > 0) {
                //获取锁仓的份数
                BigDecimal count = new BigDecimal(storages.size());
                //获取平台发放消证的所有数据
                List<FwLogs> list = logsService.list(Wrappers.<FwLogs>lambdaQuery()
                        .eq(FwLogs::getIsType, LogsTypeEnum.MONEY_INCOME.getTypeName())
                        .eq(FwLogs::getModelName, LogsModelEnum.DISAPPEAR_MODEL.getModelName())
                        .last("AND bui_id = create_by AND DATE_FORMAT( create_time, '%Y%m' ) = DATE_FORMAT( CURDATE() , '%Y%m' ) "));
                //初始化发放消证总量
                BigDecimal countDisappear = new BigDecimal("0");
                if (list.size() > 0) {
                    //遍历平台发放消证的所有数据
                    for (FwLogs logs : list) {
                        countDisappear = countDisappear.add(new BigDecimal(logs.getFormInfo()));
                    }
                    //计算出每一份多少分红
                    //嵌入公式    消证总量 *规则的万分比/ 锁仓的份数
                    BigDecimal moneyNo = BigDecimal.ZERO;
                    BigDecimal resultNumJifen = new BigDecimal(0);
                    if (count.compareTo(BigDecimal.ZERO) > 0) {
                        //计算出的整体要分红的数量
                        moneyNo = countDisappear.multiply(ruleCount).divide(new BigDecimal(10000), BigDecimal.ROUND_HALF_UP);
                        //计算出来的最终的每一份的分红积分数量
                        resultNumJifen = moneyNo.divide(count, 4, BigDecimal.ROUND_HALF_UP);
                    }

                    if (resultNumJifen.compareTo(new BigDecimal(0.001)) > 0) {
                        for (FwLockStorage lockStorage : storages) {
                            String userId = lockStorage.getUserId();
                            //获取用户钱包数据
                            FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
                            //发放分红
                            moneys.setIntegral(moneys.getIntegral().add(resultNumJifen));
                            moneysService.updateById(moneys);
                            //新增日志分红
                            logsService.saveLogs(userId, userId, LogsTypeEnum.INTEGRAL_BONUS.getTypeName(), LogsModelEnum.INTEGRAL_MODEL.getModelName(), "分红得到" + resultNumJifen + "积分", resultNumJifen.toString());
                        }
                        //todo 在日志表里增加一条日志标记这个月已经分过红了 然后上边分红的时候去日志表验证是否还继续执行逻辑
                        logsService.saveLogs("1", "1", LogsTypeEnum.SYS_BONUS.getTypeName(), LogsModelEnum.SYS_BONUS.getModelName(), "系统已分红" + count + "份", "总共分了" + moneyNo.toString());
                    }
                }
            }
        }
        throw new BaseException("当前月份已经分过红,不可在分红!");

    }
}
